﻿using FC.ERP.TMom.Api.AppHandlers.Commands.EssentialDatas.FactoryManages.Lines;
using FC.ERP.TMom.Api.DTOs;
using FC.ERP.TMom.Domain;
using FC.ERP.TMom.ErrorCode;
using FC.ERP.TMom.Infrastructure.Interfaces;
using MediatR;

namespace FC.ERP.TMom.Api.AppHandlers.CommandHandlers.EssentialDatas.FactoryManages.Lines
{
    public class LineQuertyCommandHandler : IRequestHandler<LineQuertyCommand, APIResult<APIPaging<LineDTO>>>
    {
        private readonly IBaseRepository<Line> linerepository;
        private readonly IBaseRepository<WorkShop> workShoprepository;
        public LineQuertyCommandHandler(IBaseRepository<Line> linerepository, IBaseRepository<WorkShop> workShoprepository)
        {
            this.linerepository = linerepository;
            this.workShoprepository = workShoprepository;
        }

        public Task<APIResult<APIPaging<LineDTO>>> Handle(LineQuertyCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<LineDTO>> result = new APIResult<APIPaging<LineDTO>>();
            result.Code=ResultCode.查询成功;
            result.Message=ResultCode.查询成功.ToString();
            var list = from a in linerepository.GetAll()
                       join b in workShoprepository.GetAll() on a.WorkShoplId equals b.WorkShopId

                       where !a.IsDeleted
                       select new LineDTO
                       {
                           LineId=a.LineId,
                           LineCode=a.LineCode,
                           LineName=a.LineName,
                           Description=a.Description,
                           WorkShoplId=a.WorkShoplId,
                           WorkShopName=b.WorkShopName,
                           CreateId=a.CreateId,
                           CreateTime=a.CreateTime,
                           UpdateTime=a.UpdateTime
                       };
            int totalCount = list.Count();
            int totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            list = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            APIPaging<LineDTO> entity = new APIPaging<LineDTO>();
            entity.TotalCount = totalCount;
            entity.TotalPage = totalPage;
            entity.List = list.ToList();
            result.Data = entity;

            return Task.FromResult(result);
        }
    }
}
